package cn.nexttec.noteplayer.ui.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import cn.nexttec.noteplayer.common.formatDate
import cn.nexttec.noteplayer.models.NoteFile
import com.gci.lib_markdown_editor.databinding.ItemNoteBinding

class NoteAdapter (val onItemClicked:(NoteFile)->Unit, val onItemLongClicked:((NoteFile)->Unit)?= null) :RecyclerView.Adapter<NoteAdapter.ViewHolder>(){
    private val notes = ArrayList<NoteFile>()

    inner class ViewHolder(val binding:ItemNoteBinding):RecyclerView.ViewHolder(binding.root){
        fun bind(noteFile: NoteFile){
            binding.title.text = noteFile.name
            binding.info.text = formatDate(noteFile.updatedAt)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemNoteBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return notes.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val note = notes[position]
        holder.bind(note)
        holder.binding.root.setOnClickListener{
            onItemClicked(note)
        }

        holder.binding.root.setOnLongClickListener {
            onItemLongClicked?.invoke(note)
            true
        }
    }

    fun appendNotes(list: List<NoteFile>?) {
        notes.clear()
        list?.let{
            notes.addAll(it)
            notifyDataSetChanged()
        }
    }

    fun clear() {
        notes.clear()
    }
}